package xyz.jcat.webmvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 默认请求参数转换器配置类
 */
@Configuration
public class DefaultConverterConfig {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void addDefaultConverters() {
        ConfigurableWebBindingInitializer configurableWebBindingInitializer =
                (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        GenericConversionService genericConversionService =
                (GenericConversionService) configurableWebBindingInitializer.getConversionService();
        genericConversionService.addConverter(new DateConverter());
    }

    /**
     * 日期转换器，时间戳转日期
     */
    public class DateConverter implements Converter<String, Date> {

        @Override
        public Date convert(String timestamp) {
            return new Date(Long.valueOf(timestamp));
        }

    }

}
